import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class CalfAccountSQL {
  final List<String> _tableSchemaSQL;
  final String _dropTableSQL = "DROP TABLE IF EXISTS %s";

  CalfAccountSQL(this._tableSchemaSQL);

  Future<Database> get db async {
    return _initDb();
  }

  Future<Database> _initDb() async {
    String basePath = await getDatabasesPath();
    String path = join(basePath, "calf_account.db");
    Database db = await openDatabase(path,
        version: 1, onCreate: _onCreate, onUpgrade: _onUpgrade);
    return db;
  }

  void _onCreate(Database db, int newVersion) async {
    print("_onCreate newVersion:$newVersion");
    var batch = db.batch();
    for (String sql in _tableSchemaSQL) {
      batch.execute(sql);
    }
    await batch.commit();
  }

  void _onUpgrade(Database db, int oldVersion, int newVersion) async {
    print("_onUpgrade oldVersion:$oldVersion");
    print("_onUpgrade newVersion:$newVersion");

    var batch = db.batch();
    if (oldVersion == 1) {
      batch.execute(_dropTableSQL);
    }

    await batch.commit();
  }
}
